#include "ChatWidget.h"
#include <QScrollBar>
#include <QMessageBox>

ChatWidget::ChatWidget(QWidget* parent)
    : QWidget(parent), m_client(new ChatClient(this))
{
    setupUI();
    setupConnections();
}

ChatWidget::~ChatWidget()
{
}

void ChatWidget::setupUI()
{
    setWindowTitle("Qt6 聊天室");
    //setMinimumSize(800, 600);

    // 在线用户列表
    m_onlineUsersList = new QListWidget();
    m_onlineUsersList->setMaximumWidth(200);

    // 聊天历史区域
    m_chatHistoryList = new QListWidget();
    m_chatHistoryList->setAlternatingRowColors(false);

    // 消息输入区域
    m_messageEdit = new QTextEdit();
    m_messageEdit->setMaximumHeight(80);
    m_messageEdit->setPlaceholderText("输入消息...");

    m_sendButton = new QPushButton("发送");
    m_sendButton->setFixedSize(80, 40);

    m_statusLabel = new QLabel("未连接");
    m_statusLabel->setStyleSheet("color: red; padding: 5px;");

    // 输入区域布局
    auto* inputLayout = new QHBoxLayout();
    inputLayout->addWidget(m_messageEdit);
    inputLayout->addWidget(m_sendButton);

    // 主布局
    auto* splitter = new QSplitter(Qt::Horizontal);
    splitter->addWidget(m_onlineUsersList);
    splitter->addWidget(m_chatHistoryList);
    splitter->setStretchFactor(1, 1);

    auto* mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(m_statusLabel);
    mainLayout->addWidget(splitter);
    mainLayout->addLayout(inputLayout);
}

void ChatWidget::setupConnections()
{
    connect(m_sendButton, &QPushButton::clicked, this, &ChatWidget::onSendMessage);
    connect(m_client, &ChatClient::loginSuccess, this, &ChatWidget::onLoginSuccess);
    connect(m_client, &ChatClient::messageReceived, this, &ChatWidget::onMessageReceived);
    connect(m_client, &ChatClient::connected, this, [this]() { onConnectionStatusChanged(true); });
    connect(m_client, &ChatClient::disconnected, this, [this]() { onConnectionStatusChanged(false); });
    connect(m_client, &ChatClient::errorOccurred, this, &ChatWidget::onConnectionError);
}

void ChatWidget::onLoginSuccess(const model::UserInfo& userInfo)
{
    m_currentUser = userInfo;
    m_statusLabel->setText("已连接: " + userInfo.nickname);
    m_statusLabel->setStyleSheet("color: green; padding: 5px;");
}

void ChatWidget::onMessageReceived(const model::Message& message)
{
    addMessageToChat(message);
}

void ChatWidget::onConnectionStatusChanged(bool connected)
{
    if (!connected) {
        m_statusLabel->setText("连接已断开");
        m_statusLabel->setStyleSheet("color: red; padding: 5px;");
    }
}

void ChatWidget::onSendMessage()
{
    QString text = m_messageEdit->toPlainText().trimmed();
    if (text.isEmpty()) {
        return;
    }

    // 创建消息[citation:5]
    model::Message message = model::Message::makeTextMessage(
        "general", // 默认会话ID
        m_currentUser,
        text
    );

    // 添加到聊天历史
    addMessageToChat(message);

    // 发送到服务器
    m_client->sendMessage(message);

    // 清空输入框
    m_messageEdit->clear();
    m_messageEdit->setFocus();
}

void ChatWidget::onConnectionError(const QString& error)
{
    QMessageBox::warning(this, "连接错误", error);
}

void ChatWidget::addMessageToChat(const model::Message& message)
{
    bool isOwnMessage = (message.sender.userId == m_currentUser.userId);

    auto* messageWidget = new MessageWidget(message, isOwnMessage);
    auto* listItem = new QListWidgetItem(m_chatHistoryList);

    listItem->setSizeHint(messageWidget->sizeHint());
    m_chatHistoryList->setItemWidget(listItem, messageWidget);
    m_chatHistoryList->scrollToBottom();
}
